package com.leetcode.dfs;

import com.oracle.xmlns.internal.webservices.jaxws_databinding.XmlOneway;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum2 {

    private List<List<Integer>> ans = new ArrayList<>();
    private List<int[]> freq = new ArrayList<>();
    private List<Integer> sequence = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        for (int candidate : candidates) {
            if (freq.isEmpty() || freq.get(freq.size()-1)[0] != candidate) {
                freq.add(new int[]{candidate, 1});
            } else {
                freq.get(freq.size()-1)[1]++;
            }
        }
        dfs(0, target);
        return ans;
    }

    public void dfs(int ind, int rest) {
        if (rest == 0) {
            ans.add(new ArrayList<>(sequence));
            return;
        }
        if (ind == freq.size() || rest < freq.get(ind)[0]) {
            return;
        }
        dfs(ind + 1, rest);
        int most = Math.min(rest/freq.get(ind)[0], freq.get(ind)[1]);
        for (int i = 1; i <= most; i++) {
            sequence.add(freq.get(ind)[0]);
            dfs(ind + 1, rest - i * freq.get(ind)[0]);
        }
        for(int i = 1; i <= most; i++) {
            sequence.remove(sequence.size() - 1);
        }
    }
}
